<?php
/**
 * Created by PhpStorm.
 * User: shadow
 * Date: 2017/1/15
 * Time: 14:10
 */
//add log file path
$filePath = "/var/log/nginx/error.log";

//read 50KB per page预留分页算法
$perpage = 51200; // 50KB

if (!file_exists($filePath)){
    die('该文件不存在，请检查文件路径：'.$filePath);
}
$content = file_get_contents($filePath);
$logSize = filesize($filePath);

if (!$content) {
    die('文件读取失败，请检查是否有读取权限');
}
$contents=explode("\n",$content);
$datas=[];
foreach ($contents as $content) {
    $datas[]=read_log_line($content);
}
$ignores=array_filter($GLOBALS['skipped_lines']);
foreach ($ignores as $ignore) {
    $datas[]=read_ignore_line($ignore);
}
$datas=array_filter($datas);
$logs=[];
foreach ($datas as $data) {
    $requests=explode('&',$data['request']);
    $data['request']=implode("<br>&",$requests);
    $logs[$data['ago']]=$data;
}
foreach ($logs as $index => $log) {
    $date=ago($log['ago']);
    $logs[$index]['date']=$date;
}
krsort($logs);
echo json_encode(array_values($logs));

function getfilesize($a)
{
    $unim = array("B", "KB", "MB", "GB", "TB", "PB");
    $c = 0;
    while ($a >= 1024) {
        $c++;
        $a = $a / 1024;
    }
    return number_format($a, ($c ? 2 : 0), ".", " ") . " " . $unim[$c];
}

function read_log_line($line)
{
    $info = array();
    $line = utf8_encode($line);

    if (!preg_match('`^(:?(.+\s[\:0-9]+)\s\[[^\]]+\][\s0-9\:#\*]+(.+?))(, client:.*)`u', $line, $m)) {
        $GLOBALS['skipped_lines'][] = $line;
        return false;
    }
    $info['ago'] = strtotime($m[2]);

    $info['errorno'] = '';
    $info['error'] = htmlspecialchars($m[3], ENT_QUOTES);
    if (stristr($line, 'fastcgi://')) {
        $info['errorno'] = 'PHP';
        $info['error'] = preg_replace('`(&quot;|FastCGI sent in stderr:|PHP message:|while reading response header from upstream)`i', '', $info['error']);
    } elseif (stristr($m[3], 'basic authentication')) {
        $info['errorno'] = '401';
    } elseif (stristr($m[3], 'No such file or directory')) {
        $info['errorno'] = '404';
    } elseif (stristr($m[3], ' forbidden')) {
        $info['errorno'] = '403';
    } elseif (stristr($m[3], 'Connection timed out')) {
        $info['errorno'] = '110';
    }

    $m = preg_split('`,\s([^\:]+)\:\s`u', $m[4], -1, PREG_SPLIT_DELIM_CAPTURE);

    for ($i = 1, $n = count($m); $i < $n; $i++)
        $info[$m[$i]] = htmlspecialchars(preg_replace('`(^"|"$)`u', '', $m[++$i]), ENT_QUOTES);

    if (empty($info['host']))
        $info['host'] = 'torrent-finder.info';
    if (empty($info['referrer']))
        $info['referrer'] = '';
    if (empty($info['request']))
        $info['request'] = '';
    $info['line'] = htmlspecialchars($line, ENT_QUOTES);
    return $info;
}

function read_ignore_line($line)
{
    if(strstr($line,'error')){
        $info=[
            'ago'=>0,
            'errorno'=>'',
            'error'=>'',
            'client'=>'',
            'server'=>'',
            'request'=>'',
            'upstream'=>'',
            'host'=>'',
            'referrer'=>'',
        ];
        preg_match('/\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}/',$line,$date);
        if($date){
            $info['ago']=strtotime($date[0]);
            if (stristr($line, 'FastCGI')) {
                $info['errorno'] = 'PHP';
                $error=preg_replace('/\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2} \[error\] [\s0-9\:#\*]{1,30}/','',$line);
                $info['error'] = preg_replace('`(&quot;|\"|FastCGI sent in stderr:|PHP message:|while reading response header from upstream)`i', '', explode(',',$error)[0]);
            }else{
                $info['errorno'] = 'PHP';
                $info['error']=str_replace(":",":<br>",$line);
            }
        }
        return $info;
    }
}

function ago($original)
{
    // array of time period chunks
    $chunks = array(
        array(60 * 60 * 24 * 365, 'year'),
        array(60 * 60 * 24 * 30, 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24, 'day'),
        array(60 * 60, 'hour'),
        array(60, 'minute'),
    );

//    $today = time(); /* Current unix time  */
    $since = time() - $original;
    if ($since < 0)
        return $original;

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];

        // finding the biggest chunk (if the chunk fits, break)
        if (($count = floor($since / $seconds)) != 0) {
            // DEBUG print "<!-- It's $name -->\n";
            break;
        }
    }

    $print = ($count == 1) ? '1 ' . $name : "$count {$name}s";

    if ($i + 1 < $j) {
        // now getting the second item
        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];

        // add second item if it's greater than 0
        if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
            $print .= ($count2 == 1) ? ', 1 ' . $name2 : ", $count2 {$name2}s";
        }
    }
    return "$print ago";
}
